﻿using System;
using System.Data;
using System.Text;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using GC2.Bussines;
using GC2.Bussines.BMAdmin;
using GC2.Entities.Admin;
using GC2.ExceptionHandler;

public partial class Stock_StockAdmin : GenericPage
{
    Stock stockActual = new Stock();    
    List<Stock> listaStock = new List<Stock>();
    private ExceptionConstructor exNew = new ExceptionConstructor();
    GC2.Funciones.General.FunctionsSite f = new GC2.Funciones.General.FunctionsSite();

    #region Controles

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            SetearCultura();
            SetearConexion();
            if (!IsPostBack)
            {
                Limpiar();
                btnNuevo.Enabled = false;
                lblAccion.Text = "Buscar lista y Crear Nuevo";
            }
        }
        catch (Exception ex) { ErrorUI(ex); }
    }
    #endregion

    #region btnCancelar_Click
    protected void btnCancelar_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Seguridad/Default.aspx", false);
    }
    #endregion

    #region gvStock_RowDataBound
    /// <Summary>
    /// Boundeo de la grilla
    /// CBendayan 23/03/2010 
    /// </Summary>
    /// <returns></returns>
    protected void gvStock_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        try
        {
            CheckBox chkLote;
            
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                chkLote = (CheckBox)e.Row.Cells[6].FindControl("chkLotes");
                if (listaStock[e.Row.RowIndex + (gvStock.PageIndex * 15)].UsaLotes == 1)
                {
                    chkLote.Checked = true;
                }
                else
                {
                    chkLote.Visible = false;
                }
            }
        }
        catch (Exception ex) { ErrorUI(ex); }
    }
    #endregion

    #region gvStock_PageIndexChanging
    protected void gvStock_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        try
        {
            gvStock.PageIndex = e.NewPageIndex;
            CargarGrilla();
        }
        catch (Exception ex) { ErrorUI(ex); }
    }
    #endregion

    #region gvStock_SelectedIndexChanged
    protected void gvStock_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            BMStock bmStock = new BMStock(Connection);
            Stock stock = new Stock();
            int iArt =  (int)gvStock.SelectedDataKey.Value;
            listaStock = (List<Stock>)Session["listaStock"];
            foreach (Stock articulo in listaStock)
            {
                if (iArt == articulo.Id_Articulo)
                {
                    stock = articulo;
                    break;
                }
            }
            if (stock.Id_Articulo > 0)
            {
                stockActual = stock;
                stock = bmStock.BMStockGetOne(stockActual);
                Session["Stock"] = stock;
                Session["Accion"] = 2;
                Response.Redirect("StockGestion.aspx", false);
            }
            else
            {
                /// mensaje Error Articulo no encontrado
                mpeError.Show();
            }
        }
        catch (Exception ex) { ErrorUI(ex);}
    }
    #endregion

    #region btnBuscar_Click
    protected void btnBuscar_Click(object sender, EventArgs e)
    {
        try
        {
            BMStock bmStock = new BMStock(Connection);
            Stock stock = new Stock();
            stock.Id_Rubro = Convert.ToInt16(Rubros1.CboRubro.SelectedValue);

            if (Rubros1.CboSubRubro.SelectedValue != "")
            {
                stock.Id_SubRubro = Convert.ToInt16(Rubros1.CboSubRubro.SelectedValue);
                btnNuevo.Enabled = true;
            }
            
            stock.Articulo = txtArticulo.Text;
            if (txtCodigo.Text.Trim() != "" && f.isNumeric(txtCodigo.Text))
                stock.Id_Articulo = Convert.ToInt16(txtCodigo.Text.Trim());
            listaStock = bmStock.BMStockSearch(stock);
            Session["listaStock"] = listaStock;
            if (listaStock.Count > 0)
            {
                lblAccion.Text = "Muestra lista de Art&iacute;culos";
            }
            CargarGrilla();
        }
        catch (Exception ex) { throw ex; }
    }
    #endregion

    #region btnNuevo_Click
    protected void btnNuevo_Click(object sender, EventArgs e)
    {
        try
        {
            Stock stock = new Stock();
            stock.Id_Rubro = Convert.ToInt16(Rubros1.CboRubro.SelectedValue);
            stock.Rubro = Rubros1.CboRubro.SelectedItem.Text;
            if (Rubros1.CboSubRubro.SelectedValue == "")
            {
                lblAccion.Text = "No se puede cargar Nuevo sin Sub Rubro.";
                return;
            }
            stock.Id_SubRubro = Convert.ToInt16(Rubros1.CboSubRubro.SelectedValue);
            stock.SubRubro = Rubros1.CboSubRubro.SelectedItem.Text;
            Session["Stock"] = stock;
            Session["Accion"] = 1;
            Response.Redirect("StockGestion.aspx", false);
        }
        catch (Exception ex) { throw ex; }
    }
    #endregion

    #region btnInforme_Click
    protected void btnInforme_Click(object sender, EventArgs e)
    {
        try
        {
            if (Session["listaStock"] != null)
            {
                List<Stock> listaStock = (List<Stock>)Session["listaStock"];
                if (listaStock.Count > 0)
                {
                    Session["iReporte"] = 1;
                    Session["pFecha"] = DateTime.Now;
                    string sRubro = listaStock[0].Id_Rubro.ToString();
                    sRubro += " ";
                    sRubro += listaStock[0].Rubro;
                    Session["pRubro"] = sRubro;
                    string sSubRubro = listaStock[0].Id_SubRubro.ToString();
                    sSubRubro += " ";
                    sSubRubro += listaStock[0].SubRubro;
                    Session["pSubRubro"] = sSubRubro;

                    registrarScript();
                }
                else
                {
                    lblAccion.Text = "No hay datos para generar Informe";
                }
            }
            else
            {
                lblAccion.Text = "No hay datos para generar Informe";
            }
        }
        catch (Exception ex) { ErrorUI(ex); }
    }
    #endregion

    #endregion

    #region Métodos

    #region CargarGrilla
    private void CargarGrilla()
    {
        try
        {
            listaStock = (List<Stock>)Session["listaStock"];
            gvStock.DataSource = listaStock;
            gvStock.DataBind();
        }
        catch (Exception ex) { throw ex; }
    }
    #endregion

    #region Limpiar
    private void Limpiar()
    {
        try
        {
            btnNuevo.Enabled = true;
            if (Session["SubRubro"] != null)
            {
                SubRubros subRubro = new SubRubros();
                subRubro = (SubRubros)Session["SubRubro"];
                if (subRubro.Id_SubRubro == 0)
                {
                    btnNuevo.Enabled = false;
                }
            }
            else
            {
                btnNuevo.Enabled = false;
            }

            listaStock = new List<Stock>();
            Session["listaStock"] = listaStock;
            gvStock.DataSource = listaStock;
            gvStock.DataBind();
        }
        catch (Exception ex) { throw ex; }
    }
    #endregion

    #region registrarScript
    protected void registrarScript()
    {
        // dispararPopUp(hacePostBack)
        StringBuilder scriptSession = new StringBuilder("<script language='javascript' type='text/javascript'>");
        scriptSession.Append("function mostrarReporte()");
        scriptSession.Append("{");
        scriptSession.Append("var stringURL = '../Informes/RptStockView.aspx';");
        scriptSession.Append("var opciones='toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes';");
        scriptSession.Append("var newWin = window.open(stringURL, 'PopUp" + DateTime.Now.Ticks.ToString() + "', opciones);");
        scriptSession.Append("}");
        scriptSession.Append("mostrarReporte();");
        scriptSession.Append("</script>");

        Page.ClientScript.RegisterStartupScript(this.GetType(), "Reporte" + Session["iReporte"].ToString(), scriptSession.ToString());
    }
    #endregion

    #endregion
}
